package com.lagou.edu.controller;

import com.google.common.util.concurrent.RateLimiter;
import com.lagou.edu.client.EmailClient;
import com.lagou.edu.entity.AuthCode;
import com.lagou.edu.service.AuthCodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yeqingyun
 * @Date: 2020/11/20 15:42
 */
@RequestMapping("/code")
@RestController
@RequiredArgsConstructor
public class AuthCodeController implements InitializingBean {

    @Value("${limit.count:0.2}")
    private Double IpLimit;
    private final AuthCodeService authCodeService;
    private final EmailClient emailClient;
    private RateLimiter rateLimiter;

    @RequestMapping("/create/{email}")
    public boolean create(@PathVariable("email") String email) {
        if (!rateLimiter.tryAcquire()) {
            return false;
        }
        //1生成验证码
        AuthCode authCode = new AuthCode();
        authCode.setCode(UUID.randomUUID().toString());
        authCode.setEmail(email);
        authCode.setCreateTime(new Date());
        authCode.setExpireTime(new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(3600)));
        authCodeService.create(authCode);
        //2发送到邮箱
        emailClient.sendCode(email, authCode.getCode());
        return true;
    }

    @RequestMapping("/validate/{email}/{code}")
    public Integer validate(@PathVariable("email") String email, @PathVariable("code") String code) {
        Optional<AuthCode> authCode = authCodeService.getByEmail(email);
        if (!authCode.isPresent()) {
            return 2;
        }
        if (!code.equals(authCode.get().getCode()) || authCode.get().getExpireTime().before(new Date())) {
            return 2;
        }

        return 0;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 每秒发出5个令牌
        rateLimiter = RateLimiter.create(IpLimit);
    }
}
